package C049;

import java.util.Arrays;

/**
 * ClassName: C07
 * Package: C049
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/17 19:15
 * @Version 1.0
 * @Since 1.0
 */
public class C07 {
    public static void main(String[] args) {
        System.out.println(longestSubstring("aaaaaaaaabbbcccccddddd", 5));
    }


    public static int longestSubstring(String s, int k) {
        char[] charArray = s.toCharArray();
        int[] cnts = new int[256];
        int res = 0;
        for (int require = 1; require <= 26; require++) {
            Arrays.fill(cnts, 0);
            for (int r = 0, l = 0, collect = 0, satisfy = 0; r < charArray.length; r++) {
                if (++cnts[charArray[r]] == 1) {
                    collect++;
                }
                if (cnts[charArray[r]] == k) {
                    satisfy++;
                }

                // 检查个数
                while (collect > require) {
                    if (cnts[charArray[l]] == 1) {
                        collect--;
                    }
                    if (cnts[charArray[l]] == k) {
                        satisfy--;
                    }
                    cnts[charArray[l++]]--;
                }

                // 计算结果
                if (satisfy == require) {
                    res = Math.max(res, r - l + 1);
                }
            }
        }
        return res;
    }

}
